using System;
using System.Collections.Generic;
using System.Linq;
using Sustainalytics.Synchronization.Validation.ValidationRules.Common;
using Sustainalytics.Synchronization.Validation.Validators;

namespace Sustainalytics.Synchronization.Validation
{
    public class InvalidCompaniesList
    {
        private static readonly object Lock = new object();

        private readonly HashSet<CompanyIdResearchProductTuple> invalidCompanies =
            new HashSet<CompanyIdResearchProductTuple>();

        private readonly HashSet<CompanyIdResearchProductTuple> newInvalidProfiles = new HashSet<CompanyIdResearchProductTuple>();

        public void AddValidationFailures(List<ValidationFailure> validationFailures)
        {
            if (validationFailures == null)
            {
                return;
            }

            var validationErrors = validationFailures.Where(x => x.Severity == Severity.Red);
            if (!validationErrors.Any())
            {
                return;
            }

            var companies = validationErrors.Select(x => new CompanyIdResearchProductTuple(x.Key, x.ResearchProduct));

            lock (Lock)
            {
                foreach (var company in companies.Where(company => !invalidCompanies.Contains(company)))
                {
                    invalidCompanies.Add(company);
                }
            }
        }

        public IList<Guid> GetCompanies(BusinessResearchProduct researchProduct)
        {
            lock (Lock)
            {
                return invalidCompanies.Where(x => x.ResearchProduct == researchProduct).Select(x => x.CompanyId).ToList();
            }
        }

        public void AddCompaniesIds(ICollection<CompanyIdResearchProductTuple> companies)
        {
            lock (Lock)
            {
                foreach (var company in companies.Where(company => !newInvalidProfiles.Contains(company)))
                {
                    newInvalidProfiles.Add(company);
                }
            }
        }
    }
}
